<?php

namespace app\admin\controller\wq;

use app\common\controller\Backend;

use app\admin\library\Auth;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
/**
 * 问卷记录管理
 *
 * @icon fa fa-circle-o
 */
class Content extends Backend
{
    
    /**
     * Content模型对象
     * @var \app\admin\model\wq\Content
     */
    protected $model = null;

    protected $noNeedLogin = ['addnew'];
    protected $noNeedRight = ['addnew'];


    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\wq\Content;

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        $url = "";
        if (isset($_SERVER['HTTP_REFERER'])) {
            $url = $_SERVER['HTTP_REFERER'];
        }

        $wq_template_id = 0;
        if (false !== strpos($url, '/ids/')) {
            $urls = explode('?', $url);
            $url = $urls[0];
            $urls = explode('/', $url);
            $size = count($urls);
            $wq_template_id = $urls[$size - 1];
            $wqtemplate = \app\admin\model\wq\Template::get($wq_template_id);
        } else {
            $url = $_SERVER['REQUEST_URI'];
            if (false !== strpos($url, '/ids/')) {
                $urls = explode('?', $url);
                $url = $urls[0];
                $urls = explode('/', $url);
                $size = count($urls);
                $wq_template_id = $urls[$size - 1];
                $wqtemplate = \app\admin\model\wq\Template::get($wq_template_id);
            }
        }

        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $where1 = "";
            if ($wq_template_id > 0) {
                $where1 = " wq_template_id = {$wq_template_id} ";
            }

            $total = $this->model
                    ->with(['template'])
                    ->where($where)
                    ->where($where1)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['template'])
                    ->where($where)
                    ->where($where1)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as &$row) {
                $jsons = json_decode($row->json, true);
                foreach ($jsons as $k => $v) {
                    $row[$k] = $v;
                }
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }

        $titles = [];
        if ($wqtemplate) {
             $jsons = json_decode($wqtemplate->json, true);
            foreach ($jsons as $k => $v) {
                $titles[] = $k;
            }
        }
        $this->assignconfig('titles', $titles);

        if ($wqtemplate) {
            $wqtemplate = $wqtemplate->toArray();
        }

        $this->view->assign("wqtemplate", $wqtemplate);

        return $this->view->fetch();
    }

    public function addnew()
    {
        $wqtemplateid = $this->request->request('wqtemplateid', 0);
        $wqtemplate = \app\admin\model\wq\Template::get($wqtemplateid);

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $params['json'] = json_encode($params);
                    $params['wq_template_id'] = $wqtemplateid;
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $html = "";
        if ($wqtemplate) {
            $jsons = json_decode($wqtemplate->json, true);
            $i = 0;
            foreach ($jsons as $k => $v) {
                $type = intval($v);
                //0|字符串  1|数字   2|日期  3|图片  4|单选  5|多选  6|状态(0 or 1）
                switch ($type) {
                    default:
                    case 0;
                        break;
                    case 1;
                        break;
                    case 2;
                        break;
                    case 3;
                        break;
                    case 4;
                        break;
                    case 5;
                        break;
                    case 6;
                        break;
                }
//                <textarea class="form-control " rows="5" name="msg" cols="80"></textarea>
                $html .= "<div class=\"form-group\"><label class=\"control-label col-xs-12 col-sm-2\">{$k}:</label><div class=\"col-xs-12 col-sm-8\"><textarea class=\"form-control \" rows=\"5\" name=\"row[c{$i}]\" cols=\"80\"></textarea></div></div>";
                $i++;
            }
        }

        $this->view->assign("wqtemplate", $wqtemplate);
        $this->view->assign("html", $html);

        return $this->view->fetch();
    }

}
